import { defineStore } from 'pinia';
import { ref } from 'vue';
import { userloginAPI, getUserDetailAPI } from '@/apis/user.js'

// 持久化存储
const getFromLocalStorage = (key) => localStorage.getItem(key) || '';
export const setFromLocalStorage = (key, value) => localStorage.setItem(key, value);
const removeFromLocalStorage = (key) => localStorage.removeItem(key);

export const useAuthStore = defineStore('auth', () => {
    const token = ref(getFromLocalStorage('token'));
    const username = ref(getFromLocalStorage('username'));
    const role = ref(getFromLocalStorage('role'));
    const userDetail = ref({});
    const LastPath = ref(getFromLocalStorage('LastPath'));

    const login = async (userInfo) => { 
        const res = await userloginAPI(userInfo);
        if(res.code === 1) {
            token.value = res.data.token;
            username.value = res.data.username;
            role.value = res.data.role;

            // 持久化到本地存储
            setFromLocalStorage('token', token.value);
            setFromLocalStorage('username', username.value);
            setFromLocalStorage('role', role.value);
        }
        return res;
    }

    const logout = () => {
        token.value = '';
        username.value = '';
        role.value = '';
        userDetail.value = {};
        localStorage.clear();
    }

    const getUserDetail = async () => {
        const res = await getUserDetailAPI();
        if(res.code === 1) {
            userDetail.value = res.data;
        }
        return res;
    }

    const updateLastPath = (newPath) => {
        LastPath.value = newPath;
        setFromLocalStorage('LastPath', newPath); 
    }

    return {
        token,
        username,
        role,
        userDetail,
        LastPath,
        login,
        logout,
        getUserDetail,
        updateLastPath,
    }
})